using Eno.Application.Dto;
using Eno.Domain.Entity.App;
using Eno.Domain.Repositories;

namespace Eno.Application.Services;

public class RoleService
{
    private readonly IRepository<AppRole> _service;

    private readonly IUserToRoleRepository _userRole;

    public RoleService(IRepository<AppRole> service, IUserToRoleRepository userRole)
    {
        _service = service;
        _userRole = userRole;
    }

    public async Task<int> AdditonRole(RoleDto roleDto)
    {
        var obj = await _service.GetRoleByNameAsync(roleDto.RoleName);
        if (obj != null) return 0;
        var role = new AppRole
        {
            ID = Guid.NewGuid(),
            RoleName = roleDto.RoleName,
            DataRange = roleDto.DataRange,
            IsActived = roleDto.IsActived,
            Remarks = roleDto.Remarks
        };
        return await _service.AdditionRoleAsync(role);
    }

    public async Task<int> UpdateRole(Guid roleId, RoleDto roleDto)
    {
        var role = await _service.GetRoleByIdAsync(roleId);
        if (role == null) return 0;
        role.RoleName = roleDto.RoleName;
        role.DataRange = roleDto.DataRange;
        role.IsActived = roleDto.IsActived;
        role.Remarks = roleDto.Remarks;
        return await _service.UpdateRoleAsync(role);

    }

    public async Task<AppRole?> GetRoleOne(Guid roleId)
    {
        return await _service.GetRoleByIdAsync(roleId);
    }

    public async Task<int> DeleteRole(Guid roleId)
    {
        var role = _service.GetRoleByIdAsync(roleId);
        if (role == null) return 0;
        var delSelf = await _userRole.DeleteRole(roleId);
        if (delSelf < 0)
        {
            return 0;
        }
        else
        {
            var delLinkTab = await _service.DeleteRoleAsync(roleId);
            if (delLinkTab < 0)
            {
                return 0;
            }
            return delLinkTab;
        }

    }

    public async Task<AppRole?> GetIdByRoleName(string roleName)
    {
        var role = await _service.GetRoleByNameAsync(roleName);
        if (role == null)
        {
            return null;
        }
        return role;
    }

    public async Task<IEnumerable<AppRole>> GetAllRolesAsync()
    {
        return await _service.GetRoleAllAsync();
    }
}

